package com.exchange.used.config.annotation;

import com.exchange.used.config.constant.K;
import com.exchange.used.config.utils.ExcelUtil;
import com.exchange.used.config.utils.PackageUtil;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ExcelAnnotationParser {
    public static List<List<String>> getExcelData(String className){
        List<List<String>> results = new ArrayList<>();
        try {
            Class entity = Class.forName(className);
            for(int i = 0 ; i < entity.getDeclaredFields().length ; i ++){
                Field field = entity.getDeclaredFields()[i];
                String fieldName_zh = "";
                if(field.isAnnotationPresent(ExcelFieldName.class)){
                    fieldName_zh = field.getDeclaredAnnotation(ExcelFieldName.class).fieldName();
                }
                String fieldName = field.getName();
                String fieldType = field.getType().getSimpleName();
                String keyType = getKeyType(fieldName);
                List<String> colData = Arrays.asList((i+1) + "", fieldName, fieldType, keyType, fieldName_zh);
                results.add(colData);
            }
            return results;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static List<String> getExcelHeader(){
        return Arrays.asList("编号","字段","类型","约束","备注");
    }

    private static String getKeyType(String fieldName){
        if(fieldName.contains("id")){
            if(fieldName.contains("fk")){
                return "foreign key";
            }else{
                return "primary key";
            }
        }else {
            return "";
        }
    }


    public static void main(String[] args) {
        String fileName = "E:\\test\\writeExcel.xls";
        File file = new File(fileName);
        List<String> classNames = PackageUtil.getClassName(K.ENTITY_PATH);
        //先删除全部sheet，在插入
        ExcelUtil.removeAllSheet(file);
        for(int i = 0 ; i < classNames.size() ; i ++){
            String s = classNames.get(i);
            ExcelUtil.write(file, s.split("\\.")[s.split("\\.").length-1], getExcelHeader(), getExcelData(s));
        }
    }
}
